package com.sosky;

import java.util.Arrays;

/**
 * 881. 救生艇
 * <p>
 * 第 i 个人的体重为 people[i]，每艘船可以承载的最大重量为 limit。
 * 每艘船最多可同时载两人，但条件是这些人的重量之和最多为 limit。
 * 返回载到每一个人所需的最小船数。(保证每个人都能被船载)。
 * <p>
 * 示例 1：
 * <p>
 * 输入：people = [1,2], limit = 3
 * 输出：1
 * 解释：1 艘船载 (1, 2)
 * 示例 2：
 * <p>
 * 输入：people = [3,2,2,1], limit = 3
 * 输出：3
 * 解释：3 艘船分别载 (1, 2), (2) 和 (3)
 * 示例 3：
 * <p>
 * 输入：people = [3,5,3,4], limit = 5
 * 输出：4
 * 解释：4 艘船分别载 (3), (3), (4), (5)
 * 提示：
 * <p>
 * 1 <= people.length <= 50000
 * 1 <= people[i] <= limit <= 30000
 */
public class Solution881 {
    public static void main(String[] args) {
//        System.out.println(numRescueBoats(new int[]{1, 2}, 3));
//        System.out.println(numRescueBoats(new int[]{3, 2, 2, 1}, 3));
//        System.out.println(numRescueBoats(new int[]{3, 5, 3, 4}, 5));
//        System.out.println(numRescueBoats(new int[]{3, 1, 7}, 7));
        System.out.println(numRescueBoats(new int[]{5, 1, 4, 2}, 6));
    }

    public static int numRescueBoats(int[] people, int limit) {
        if (people.length == 0 || limit == 0) {
            return 0;
        }
        Arrays.sort(people);
        int boats = 0;
        for (int i = people.length - 1; i >= 0; i--) {
            if (people[i] == 0) {
                break;
            }
            if (people[i] == limit) {
                people[i] = 0;
                boats++;
            } else if (people[i] < limit) {
                for (int j = 0; j <= i; j++) {
                    if (people[j] == 0) {
                        continue;
                    }
                    if (people[i] + people[j] <= limit) {
                        people[i] = 0;
                        people[j] = 0;
                        boats++;
                        break;
                    } else {
                        people[i] = 0;
                        boats++;
                        break;
                    }
                }
            }
        }
        return boats;
    }
}
